package com.voyage.oauth.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class VoyageUserDetailsService implements UserDetailsService {


    private final PasswordEncoder passwordEncoder;

    @Autowired
    public VoyageUserDetailsService(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username is={}", username);
        // todo 此处查询数据库获取用户
        if (!"admin".equalsIgnoreCase(username)) {
            throw new UsernameNotFoundException("this user is not found");
        } else {
            // todo 此处用户角色应该从数据获取
            String role = "ADMIN_ROLE";
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(role));
            String password = passwordEncoder.encode("123");
            return new User(username, password, authorities);
        }
    }
}
